package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ReUtil;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IAppmanagerService;
import com.ruoyi.system.service.IDrinfoService;
import com.ruoyi.system.service.IDrtypeinfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IRunRecordsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 运行记录Controller
 * 
 * @author yaozh
 * @date 2024-02-20
 */
@RestController
@RequestMapping("/monitor/control")
public class RunRecordsController extends BaseController
{
    @Resource
    private IRunRecordsService runRecordsService;
    @Resource
    private IAppmanagerService appManagerService;
    @Resource
    private IDrtypeinfoService drtypeinfoService;
    @Resource
    private IDrinfoService drinfoService;

    /**
     * 查询运行记录列表
     */
    @PreAuthorize("@ss.hasPermi('monitor:control:list')")
    @GetMapping("/list")
    public TableDataInfo list(RunRecords runRecords,@RequestParam String dbName)
    {
        List<Appmanager> appList = appManagerService.selectAppManagerListByUserAndDbName(getLoginUser(),dbName);
        if(appList == null || appList.size() == 0){
            return getDataTable(new ArrayList<>());
        }
        startPage();
        List<RunRecords> list = runRecordsService.selectRunRecordsList(runRecords,dbName);
        if(list != null && list.size() > 0 && StringUtils.hasLength(dbName)){
            Integer appId = ReUtil.getFirstNumber(dbName);
            if(appId > 0){
                Appmanager appmanager = appManagerService.selectAppmanagerByAppid(Long.valueOf(appId));
                if(appmanager != null && StringUtils.hasLength(appmanager.getAppexplain())){
                    for(RunRecords runRecord : list){
                        runRecord.setProjectName(appmanager.getAppexplain());
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出运行记录列表
     */
    @PreAuthorize("@ss.hasPermi('monitor:control:export')")
    @Log(title = "运行记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RunRecords runRecords,@RequestParam String dbName)
    {
        List<Appmanager> appList = appManagerService.selectAppManagerListByUserAndDbName(getLoginUser(),dbName);
        List<RunRecords> list = new ArrayList<>();
        if(appList != null && appList.size() > 0){
            list = runRecordsService.selectRunRecordsList(runRecords,dbName);
        }
        ExcelUtil<RunRecords> util = new ExcelUtil<RunRecords>(RunRecords.class);
        util.exportExcel(response, list, "运行记录数据");
    }

    /**
     * 获取运行记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('monitor:control:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id,@RequestParam String dbName)
    {
        return success(runRecordsService.selectRunRecordsById(id,dbName));
    }

    /**
     * 新增运行记录
     */
    @PreAuthorize("@ss.hasPermi('monitor:control:add')")
    @Log(title = "运行记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RunRecords runRecords,@RequestParam String dbName)
    {
        return toAjax(runRecordsService.insertRunRecords(runRecords,dbName));
    }

    /**
     * 修改运行记录
     */
    @PreAuthorize("@ss.hasPermi('monitor:control:edit')")
    @Log(title = "运行记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RunRecords runRecords,@RequestParam String dbName)
    {
        return toAjax(runRecordsService.updateRunRecords(runRecords,dbName));
    }

    /**
     * 删除运行记录
     */
    @PreAuthorize("@ss.hasPermi('monitor:control:remove')")
    @Log(title = "运行记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids,@RequestParam String dbName)
    {
        boolean isAdmin = getLoginUser().getUser().isAdmin();
        List<SysRole> roleIdList = getLoginUser().getUser().getRoles();
        boolean isAdminBackground = false;
        for(SysRole role : roleIdList){
            Long roleId = role.getRoleId();
            if(roleId.intValue() == 2){
                //是管理员角色
                isAdminBackground = true;
            }
        }
        if(!(isAdmin || isAdminBackground)){
            String message = "拒绝操作，仅后台管理员权限才能删除！";
            throw new RuntimeException(message);
        }
        return toAjax(runRecordsService.deleteRunRecordsByIds(ids,dbName));
    }

    /**
     * 不分页，查询项目类型列表
     */
    @PreAuthorize("@ss.hasPermi('monitor:control:list')")
    @GetMapping("/listAllDrType")
    public AjaxResult listAllDrType(@RequestParam String dbName)
    {
        List<Appmanager> appList = appManagerService.selectAppManagerListByUserAndDbName(getLoginUser(),dbName);
        if(appList == null || appList.size() == 0){
            return success(new ArrayList<>());
        }
        return success(drtypeinfoService.selectDrTypeForAll(dbName));
    }

    @PreAuthorize("@ss.hasPermi('monitor:control:list')")
    @GetMapping("/listByDrTypeId/{drtypeid}")
    public AjaxResult listByDrTypeId(@PathVariable("drtypeid") Long drtypeid,@RequestParam String dbName)
    {
        List<Appmanager> appList = appManagerService.selectAppManagerListByUserAndDbName(getLoginUser(),dbName);
        if(appList == null || appList.size() == 0){
            return success(new ArrayList<>());
        }
        return success(drinfoService.selectByDrTypeId(drtypeid,dbName));
    }

}
